package com.example.day1031_dataeven.slice;

import com.example.day1031_dataeven.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Text;
import ohos.agp.components.TextField;
import ohos.agp.window.dialog.ToastDialog;
import ohos.data.search.SearchAbility;
import ohos.data.search.SearchSession;
import ohos.data.search.connect.ServiceConnectCallback;
import ohos.data.search.model.IndexData;
import ohos.data.search.model.IndexForm;
import ohos.data.search.model.IndexType;
import ohos.data.search.model.SearchParameter;
import ohos.data.search.schema.CommonItem;
import ohos.data.search.schema.IndexSchemaType;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.utils.zson.ZSONArray;
import ohos.utils.zson.ZSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class SearchDataSlice extends AbilitySlice {

    private static final HiLogLabel LABEL_LOG = new HiLogLabel(0, 0, "My_AG");

    private SearchAbility mSearchAbility;

    private Button mCreat;      // 创建连接服务
    private Button mIndex;      // 添加索引
    private Button mSearch;      // 融合搜索
    private Button madds;             //一键填入


    private TextField mKeyWord;     //关键字
    private Text mKeyNumber;     //关键字
    private TextField mResult;       //查询结果

    private Students stt;
    private List<Students> stu;
    private SearchDataSlice start;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_search_data);


        inits();

    }

    private void inits() {
        mCreat = (Button) findComponentById(ResourceTable.Id_ser_create_btn);
        mIndex = (Button) findComponentById(ResourceTable.Id_ser_index_btn);
        mSearch = (Button) findComponentById(ResourceTable.Id_ser_search_btn);
        madds = (Button) findComponentById(ResourceTable.Id_main_tfadds);

        mKeyWord = (TextField) findComponentById(ResourceTable.Id_ser_tfkeyword); //关键字
        mKeyNumber = (Text) findComponentById(ResourceTable.Id_ser_tkeynumber); //关键字
        mResult = (TextField) findComponentById(ResourceTable.Id_ser_tfresult);     //结果

        mCreat.setClickedListener(component -> onConnect());
        mIndex.setClickedListener(component -> CreatIndex());
        mSearch.setClickedListener(component -> queryData());
        madds.setClickedListener(component -> Adds());

    }


    private void queryData() {
        SearchSession searchSession = mSearchAbility.beginSearch(SearchParameter.DEFAULT_GROUP, getBundleName());
        String query = "";
        String keyword = mKeyWord.getText().trim();
        ZSONObject zsonObject = new ZSONObject();

        ZSONObject object = new ZSONObject();

        object.put(keyword, new ZSONArray(Arrays.asList(CommonItem.NAME)));
        zsonObject.put(SearchParameter.QUERY, object);

        query = zsonObject.toString();
        int searchHitCount = searchSession.getSearchHitCount(query);
        if (searchHitCount > 0) {
            List<IndexData> data = searchSession.search(query, 0, searchHitCount);
            String result = "";
            for (int i = 0; i < data.size(); i++) {
                IndexData indexData = data.get(i);
                result = result +"姓名:"+ indexData.get("name") + " 学号:" + indexData.get("numbers") + " 年龄:"
                        + indexData.get("age") + " 性别:" + indexData.get("gender") + " 成绩:" + indexData.get("grade")+"  ";
            }
            mResult.setText(result);
            mKeyNumber.setText("含有关键字” " + keyword + " “的数量为：" + data.size());
            mSearchAbility.endSearch(SearchParameter.DEFAULT_GROUP, getBundleName(), searchSession);
        } else {
            new ToastDialog(getContext()).setText("暂无数据"+searchHitCount).show();
            HiLog.info(LABEL_LOG, "searchHitCount:"+searchHitCount );
            HiLog.info(LABEL_LOG, "query:"+query );
            HiLog.info(LABEL_LOG, "keyword:"+keyword );
        }

    }

    public static ArrayList<IndexData> buildStudentToIndexDatas(List<Students> studies) {
        ArrayList<IndexData> indexDatas = new ArrayList<>();

        if (studies != null && studies.size() > 0) {
            for (int i = 0; i < studies.size(); i++) {
                Students stuData = studies.get(i);
                CommonItem commonItem = new CommonItem();
                commonItem.setIdentifier("" + i);
                commonItem.put("name", stuData.getName());
                commonItem.put("numbers", stuData.getNumbers());
                commonItem.put("age", stuData.getAge());
                commonItem.put("gender", stuData.getGender());
                commonItem.put("grade", stuData.getGrade());

//                HiLog.info(LABEL_LOG, "姓名" + i + ":" + stuData.getName());
//                HiLog.info(LABEL_LOG, "学号" + i + ":" + stuData.getNumbers());
//                HiLog.info(LABEL_LOG, "年龄" + i + ":" + stuData.getAge());
//                HiLog.info(LABEL_LOG, "性别" + i + ":" + stuData.getGender());
//                HiLog.info(LABEL_LOG, "成绩" + i + ":" + stuData.getGrade());

                indexDatas.add(commonItem);
            }
        }
        return indexDatas;
    }

    private void Adds() {

        stt = new Students();
        stu = stt.createStudentInfo();
        start = new SearchDataSlice();
        ArrayList<IndexData> dataList = start.buildStudentToIndexDatas(stu);


        //fails 返回插入失败的记录列表
        List<IndexData> fails = mSearchAbility.insert(SearchParameter.DEFAULT_GROUP, getBundleName(), dataList);
        if (fails.size() > 0) {
            //假如fails有数据  说明有数据插入失败
            //根据业务场景做处理
            //插入成功
            new ToastDialog(getContext()).setText("信息填入失败").show();
            HiLog.info(LABEL_LOG, "信息填入失败" + fails.size());
        } else {
            //插入成功
            new ToastDialog(getContext()).setText("信息填入成功").show();
            HiLog.info(LABEL_LOG, "信息填入成功");
        }
    }

    private void CreatIndex() {
        //清除上一次设置的索引以及索引属性
        mSearchAbility.clearIndex(SearchParameter.DEFAULT_GROUP, getBundleName(), null);
        mSearchAbility.clearIndexForm(getBundleName());

        ArrayList<IndexForm> indexFormList = new ArrayList<>();
        indexFormList.add(new IndexForm("name", IndexType.SORTED, false, true, true));
        indexFormList.add(new IndexForm("numbers", IndexType.LONG, false, true, true));
        indexFormList.add(new IndexForm("age", IndexType.LONG, false, true, true));
        indexFormList.add(new IndexForm("gender", IndexType.LONG, false, true, true));
        indexFormList.add(new IndexForm("grade", IndexType.LONG, false, true, true));
        //result：描述添加索引的结果
        int result = mSearchAbility.setIndexForm(getBundleName(), 1, indexFormList, IndexSchemaType.COMMON);
        HiLog.info(LABEL_LOG, "result：" + result);
        if (result == 1) {
            //添加索引成功
            new ToastDialog(getContext()).setText("添加索引成功").show();
            HiLog.info(LABEL_LOG, "添加索引成功");
        } else {
            //失败
            new ToastDialog(getContext()).setText("添加索引失败").show();
            HiLog.info(LABEL_LOG, "添加索引失败");
        }

    }

    private void onConnect() {
        mSearchAbility = new SearchAbility(getContext());
        mSearchAbility.connect(new ServiceConnectCallback() {
            @Override
            public void onConnect() {
                //当和融合搜索建立连接
                new ToastDialog(getContext()).setText("连接成功").show();
                HiLog.info(LABEL_LOG, "onConnect");
            }

            @Override
            public void onDisconnect() {
                //当和融合搜索断开连接
                HiLog.info(LABEL_LOG, "onDisconnect");
            }
        });
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
